<template>
  <view class="pageLayout">
    <view class="card">
      <view class="card_title">
        <u-icon size="30" name="account-fill"></u-icon>
        客户信息
      </view>
      <view class="cus_info">
        <u-row
          customStyle="margin-bottom: 10px"
          justify="space-between"
          gutter="10"
        >
          <u-col span="6">
            <view class="card_content">客户姓名：{{ form.customerName }}</view>
          </u-col>
          <u-col span="6">
            <view class="card_content"
              >客户电话：{{
                form.customerPhoneNumber ? form.customerPhoneNumber : "暂无"
              }}</view
            >
          </u-col>
        </u-row>
        <u-row
          customStyle="margin-bottom: 10px"
          justify="space-between"
          gutter="10"
        >
          <u-col span="6">
            <view class="card_content"
              >主外出人员：{{
                form.masterNickName
                  ? form.masterNickName
                  : form.masterRealName
                  ? form.masterRealName
                  : "暂无"
              }}</view
            >
          </u-col>
          <u-col span="6">
            <view class="card_content"
              >客户链接金额：{{
                form.linkSumAmount ? form.linkSumAmount : "暂无"
              }}</view
            >
          </u-col>
        </u-row>

        <u-row
          customStyle="margin-bottom: 10px"
          justify="space-between"
          gutter="10"
        >
          <u-col span="6">
            <view class="card_content"
              >用车类型：{{ useCarTypeList.get(form.useCarType) }}</view
            >
          </u-col>
          <u-col span="6">
            <view class="card_content"
              >随行搭配师：{{
                form.oneFollowNickName ? form.oneFollowNickName : "暂无"
              }}</view
            >
          </u-col>
        </u-row>
        <u-row
          customStyle="margin-bottom: 10px"
          justify="space-between"
          gutter="10"
        >
          <u-col span="6">
            <view class="card_content"
              >随行设计师1：{{
                form.twoFollowNickName ? form.twoFollowNickName : "暂无"
              }}</view
            >
          </u-col>
          <u-col span="6">
            <view class="card_content"
              >随行设计师2：{{
                form.threeFollowNickName ? form.threeFollowNickName : "暂无"
              }}</view
            >
          </u-col>
        </u-row>
        <u-row
          customStyle="margin-bottom: 10px"
          justify="space-between"
          gutter="10"
        >
          <u-col span="12">
            <view class="card_content"
              >车辆使用时间：{{
                formatTimestamp(form.useDate, "onlyDate")
              }}</view
            >
          </u-col>
        </u-row>
      </view>
    </view>
    <view class="card">
      <view class="card_title">
        <u-icon size="25" name="tags-fill"></u-icon>
        带客结果
      </view>
      <view class="cus_info">
        <u--form
          labelPosition="left"
          :model="form"
          :rules="rules"
          ref="uForm"
          labelWidth="150rpx"
        >
          <view class="base_info">
            <u-form-item label="带客结果" prop="isSigning" borderBottom>
              <u-radio-group
                v-model="form.isSigning"
                placement="row"
                :disabled="
                  !(
                    form.applyGoOutOrderState == 'Audited' ||
                    form.applyGoOutOrderState == 'UseCar'
                  )
                "
                activeColor="#a22c26"
              >
                <u-radio
                  :customStyle="{ marginRight: '8px' }"
                  v-for="(item, index) in resultList"
                  :key="index"
                  :label="item.label"
                  :name="item.value"
                >
                </u-radio>
              </u-radio-group>
            </u-form-item>
            <u-form-item
              label="租车金额"
              prop="rentalAmount"
              borderBottom
              v-if="form.useCarType === 'CarRental'"
            >
              <u--input
                v-model="form.rentalAmount"
                :disabled="
                  !(
                    form.applyGoOutOrderState == 'Audited' ||
                    form.applyGoOutOrderState == 'UseCar'
                  )
                "
                border="none"
                placeholder="请输入"
              ></u--input>
            </u-form-item>
            <u-form-item
              label="签单金额"
              prop="signingAmount"
              borderBottom
              v-if="form.isSigning"
            >
              <u--input
                v-model="form.signingAmount"
                :disabled="
                  !(
                    form.applyGoOutOrderState == 'Audited' ||
                    form.applyGoOutOrderState == 'UseCar'
                  )
                "
                border="none"
                placeholder="请输入"
              ></u--input>
            </u-form-item>

            <u-form-item
              v-if="!form.isSigning"
              label="未签约原因"
              prop="notCompletionType"
              borderBottom
              @click="
                form.applyGoOutOrderState == 'Audited' ||
                form.applyGoOutOrderState == 'UseCar'
                  ? (showNotPicker = true)
                  : (showNotPicker = false)
              "
            >
              <myPicker
                :list="hospitalityNotTypeList"
                v-model="form.notCompletionType"
                :show.sync="showNotPicker"
                @close="closeNotPicker"
                keyName="label"
                idName="value"
                title="请选择未签约原因"
                @confirm="changeNotType"
              ></myPicker>
            </u-form-item>
            <!-- <u-form-item label="联系电话" prop="customerPhone" borderBottom>
              <u--input
                v-model="form.customerPhone"
                border="none"
                :disabled="isFillIn"
                placeholder="请输入客户联系电话"
              ></u--input>
            </u-form-item> -->

            <!-- <u-form-item
              label="签单日期"
              prop="signingTime"
              v-if="form.isSigning"
              @click="
                !isFillIn ? (showDatePicker = true) : (showDatePicker = false)
              "
              borderBottom
            >
              <u--input
                v-model="form.signingTime"
                border="none"
                disable
                disabledColor="#ffffff"
                placeholder="请选择使用日期"
                @click="showDatePicker = true"
              ></u--input>
              <u-icon
                slot="right"
                name="arrow-right"
                :color="color"
                :customStyle="arrowRightStyle"
              ></u-icon>
            </u-form-item> -->
            <u-form-item
              label="租车图片"
              borderBottom
              v-if="form.useCarType == 'CarRental'"
            >
              <custom-upload
                v-model="rentFileList"
                :max-count="1"
                @change="handleFileChange"
                :disabled="
                  !(
                    form.applyGoOutOrderState == 'Audited' ||
                    form.applyGoOutOrderState == 'UseCar'
                  )
                "
              />
            </u-form-item>
            <u-form-item
              label="车辆归还"
              borderBottom
              v-if="form.useCarType == 'BusinessCar'"
            >
              <custom-upload
                v-model="fileList"
                :max-count="5"
                @change="handleFileChange"
                :disabled="
                  !(
                    form.applyGoOutOrderState == 'Audited' ||
                    form.applyGoOutOrderState == 'UseCar'
                  )
                "
              />
            </u-form-item>
            <u-form-item label="说明" prop="remark">
              <u--textarea
                :disabled="
                  !(
                    form.applyGoOutOrderState == 'Audited' ||
                    form.applyGoOutOrderState == 'UseCar'
                  )
                "
                v-model="form.remark"
                placeholder="1.签单成功请填写心得，2.未签约请填写未签约原因，3.继续带请填写说明"
                count
              ></u--textarea>
            </u-form-item>
          </view>
        </u--form>
      </view>
    </view>
    <view class="bottom_btn">
      <u-button
        v-if="
          (form.applyGoOutOrderState == 'Audited' ||
            form.applyGoOutOrderState == 'UseCar') &&
          !form.hasApprove
        "
        class="btn"
        :loading="loading"
        @click="submit"
        size="small"
        shape="circle"
        color="#a22d27"
        customStyle="margin-left: 20rpx;padding:8rpx 22rpx;border:1rpx solid #A22C26;color: #ffffff;font-weight:700;"
        >提交</u-button
      >
      <!-- <u-button
        v-if="form.hasApprove"
        class="btn"
        :loading="loading"
        @click="handelCheck"
        size="small"
        shape="circle"
        color="#a22d27"
        customStyle="margin-left: 20rpx;padding:8rpx 22rpx;border:1rpx solid #A22C26;color: #ffffff;font-weight:700;"
        >同意</u-button
      >
      <u-button
        v-if="form.hasApprove"
        class="btn"
        :loading="loading"
        @click="handelCheck"
        size="small"
        shape="circle"
        color="#a22d27"
        :plain="true"
        customStyle="margin-left: 20rpx;padding:8rpx 22rpx;border:1rpx solid #A22C26;font-weight:700;"
        >拒绝</u-button
      > -->
    </view>
    <u-datetime-picker
      :show="showDatePicker"
      v-model="Date"
      mode="date"
      @confirm="changeDatePicker"
      @cancel="showDatePicker = false"
      :minDate="yearTimestamp"
      :immediateChange="true"
    ></u-datetime-picker>
    <mytoast ref="toastRef" />
  </view>
</template>

<script>
import store from "../../store/index";
import {
  QueryHospitalityResultDetailByIDApi,
  UpdateHospitaltyResultApi,
} from "@/api/withCustom/index";
import myPicker from "@/components/myPicker";
import mytoast from "@/components/mytoast.vue";
import customUpload from "@/components/customUpload.vue";

export default {
  components: {
    myPicker,
    mytoast,
    customUpload,
  },
  data() {
    return {
      todayTimestamp: "",
      yearTimestamp: "",
      showNotPicker: false, //签约结果
      showDatePicker: false, //签单日期
      id: "",
      isFillIn: false,
      Date: null,
      fileList: [],
      rentFileList: [],
      updataForm: {
        //修改的form模板保持不变用于获取修改的值
        notCompletionType: "",
        // signingAmount: null,
        isSigning: null,
        // signingTime: "",
        remark: "",
        carReturnImage: [],
        resultID: null,
        rentalAmount: null,
      },
      form: {
        applyGoOutOrderState: "",
        notCompletionType: "",
        // signingAmount: null,
        isSigning: false,
        // signingTime: "",
        remark: "",
        carReturnImage: [],
        resultID: null,
        rentalAmount: null,
      },
      useCarTypeList: new Map([
        ["BusinessCar", "公司商务车"],
        ["PrivateCar", "私家车"],
        ["CarRental", "租车"],
      ]),
      resultList: [
        // 签约状态
        {
          label: "签约",
          value: true,
        },
        {
          label: "未签约",
          value: false,
        },
        // {
        //   label: "继续带",
        //   value: "contain",
        // },
      ],
      hospitalityNotTypeList: [
        // 签约状态
        {
          label: "客户原因",
          value: "CustomerReasons",
        },
        {
          label: "工厂原因",
          value: "FactoryReasons",
        },
        {
          label: "个人原因",
          value: "MySelfReasons",
        },
      ],
      rules: {
        // 验证规则
        // signingAmount: [
        //   {
        //     type: "string",
        //     required: true,
        //     validator: (rule, value, callback) => {
        //       // 上面有说，返回true表示校验通过，返回false表示不通过
        //       // uni.$u.test.amount()就是返回true或者false的
        //       return uni.$u.test.amount(value);
        //     },
        //     message: "请输入正确金额",
        //     trigger: ["change", "blur"],
        //   },
        // ],
        carCode: [
          {
            type: "string",
            required: true,
            message: "请选择车辆",
            trigger: ["blur", "change"],
          },
        ],
        notCompletionType: [
          {
            type: "string",
            required: true,
            message: "请选择未签约原因",
            trigger: ["blur", "change"],
          },
        ],
        // signingTime: [
        //   {
        //     type: "string",
        //     required: true,
        //     message: "请选择日期",
        //     trigger: ["blur", "change"],
        //   },
        // ],
        rentalAmount: [
          {
            type: "string",
            required: true,
            message: "请输入",
            trigger: ["blur"],
          },
        ],
      },
    };
  },
  computed: {
    hasLogin() {
      return this.$store.state.token && this.$store.state.token.length > 0;
    },
  },
  methods: {
    /**
     * 获取时间选择范围
     */
    getDateSele() {
      const { todayZero, afterTomorrowZero, startOfYearTimestamp } =
        this.getZeroTimestamps();
      this.todayTimestamp = todayZero;
      this.yearTimestamp = startOfYearTimestamp;
      // this.MaxTimestamp = afterTomorrowZero;
      this.Date = todayZero;
    },
    /**
     * 获取当天和后天零点时间戳
     * @param {boolean} isUTC 是否使用UTC时间
     * @returns { todayZero: number, afterTomorrowZero: number }
     */
    getZeroTimestamps(isUTC = false) {
      const getZeroDate = () => {
        const date = new Date();
        date.setHours(0, 0, 0, 0);
        return date;
      };

      // 当天零点
      const todayZero = getZeroDate().getTime();
      const startOfYearTimestamp = new Date(
        new Date().getFullYear(),
        0,
        1
      ).getTime();

      // 明天零点
      const afterTomorrowDate = getZeroDate();
      afterTomorrowDate.setDate(afterTomorrowDate.getDate() + 1);
      const afterTomorrowZero = afterTomorrowDate.getTime();

      return { todayZero, afterTomorrowZero, startOfYearTimestamp };
    },
    /**
     * 图片上传反馈
     * @param files 当前文件列表
     */
    handleFileChange(files) {
      console.log("当前文件列表:", files);
    },
    /**
     * 日期选择
     */
    changeDatePicker(val) {
      console.log(val, "date");
      let date = this.formatTimestamp(val.value, "onlyDate") + " 00:00:00";
      this.form.signingTime = date;
      this.showDatePicker = false;
      console.log(this.form.useDate);
    },
    /**
     * 未签约原因选择器
     */
    closeNotPicker() {
      this.showNotPicker = false;
    },
    changeNotType(value) {
      console.log("changeNotType", value);
    },
    /**
     * 获取详情
     */
    async getDetail() {
      let data = { applyGoOutOrderID: this.id };
      let res = await QueryHospitalityResultDetailByIDApi(data);
      console.log(res, "res");
      this.form = res.data;
      console.log(this.imgUrl, "imgUrl");
      this.form.isSigning = res.data.isSigning ? true : false;
      this.form.rentalAmount = res.data.carRentalAmount
        ? res.data.carRentalAmount
        : "";
      // this.form.notCompletionType = "";
      if (res.data.carReturnImage != null) {
        this.fileList = res.data.carReturnImage.split(",").map((item) => {
          return {
            path: item,
            url: this.imgUrl + "/" + item,
            status: "success",
          };
        });
      }
      if (res.data.rentalImage != null) {
        this.rentFileList = res.data.rentalImage.split(",").map((item) => {
          return {
            path: item,
            url: this.imgUrl + "/" + item,
            status: "success",
          };
        });
      }
      let that = this;
      
    },
    /**
     * 提交
     */
    async submit() {
      console.log(this.form);
      console.log(this.fileList);
      if (this.fileList.length == 0 && this.form.useCarType == "BusinessCar") {
        this.$refs.toastRef.showToast({
          msg: "请上传车辆归还图片",
          duration: 2000,
          position: "center",
        });
        return;
      }
      if (
        this.rentFileList.length == 0 &&
        this.form.useCarType == "CarRental"
      ) {
        this.$refs.toastRef.showToast({
          msg: "请上传租车",
          duration: 2000,
          position: "center",
        });
        return;
      }
      let action = await this.$refs.uForm.validate();
      let imgArr = this.fileList.map((item) => {
        if (item.path != "" && item.path != undefined) {
          return item.path;
        }
      });
      let rentImgArr = this.rentFileList.map((item) => {
        if (item.path != "" && item.path != undefined) {
          return item.path;
        }
      });
      this.form.carReturnImage = imgArr.toString();
      this.form.rentalImage = rentImgArr.toString();
      let data = {
        useCarType: this.form.useCarType,
        notCompletionType: this.form.notCompletionType,
        isSigning: this.form.isSigning,
        signingAmount: this.form.signingAmount,
        rentalImage: this.form.rentalImage,
        remark: this.form.remark,
        carReturnImage: this.form.carReturnImage,
        carNumber: this.form.carNumber,
        rentalAmount: this.form.rentalAmount,
        applyGoOutOrderID: this.id,
        // signingAmount: Number(this.form.signingAmount),
      };
      // for (const [key, value] of Object.entries(this.updataForm)) {
      //   data[key] = this.form[key];
      // }
      console.log(data, "data");


      if (action) {
        this.loading = true;
        UpdateHospitaltyResultApi(data)
          .then((res) => {
            console.log(res, "res");
            this.$refs.toastRef.showToast({
              msg: "提交成功",
              duration: 2000,
              position: "center",
            });
            this.loading = false;
            uni.navigateBack({ delta: 1 });
          })
          .catch((e) => {
            uni.hideToast();
            // console.log(e,'e');
            this.loading = false;
            this.$refs.toastRef.showToast({
              msg: e.data.detail,
              duration: 2000,
              position: "center",
            });
          });
      }
    },
  },
  onShow() {
    this.getDateSele();
  },
  onLoad(options) {
    console.log(options, "options");
    this.id = options.id;
    if (options.isFillIn === "false") {
      this.isFillIn = false;
    } else if (options.isFillIn === "true") {
      this.isFillIn = true;
    }
    this.getDetail();
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules);
  },
  /**
   * 上拉加载更多
   */
  onReachBottom() {},
};
</script>
<style>
page {
  background-color: #f5f7fb;
}
</style>
<style lang="scss" scoped>
.pageLayout {
  padding: 40rpx;
  box-sizing: border-box;
}
.card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
  .card_title {
    display: flex;
    align-items: center;
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
  .card_content {
    font-size: 24rpx;
    margin-bottom: 20rpx;
  }
}
.bottom_btn {
  // position: fixed;
  // bottom: 50rpx;
  width: 90%;
  left: 50%;
  margin-top: 30rpx;
  // transform: translateX(-50%);
  display: flex;
}
</style>
